package cn.zxinrun.wps.plugins.policy;

import com.deepoove.poi.data.RowRenderData;
import com.deepoove.poi.policy.DynamicTableRenderPolicy;
import com.deepoove.poi.policy.TableRenderPolicy;
import com.deepoove.poi.util.TableTools;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;

import java.util.List;

/**
 * 自定义动态表格策略（该策略供参考）
 * <pre>
 *     使用方式：
 *     1、从data中获取表格数据：{@code List<RowRenderData> detailData = (List<RowRenderData>) data;}
 *     2、删除表格中原有的行（一般是删除头部）：{@code xwpfTable.removeRow(2);}
 *     3、循环遍历数据，插入新行并渲染数据
 *     4、合并单元格（如果需要）：
 *          1）垂直方向上合并：{@code TableTools.mergeCellsVertically(xwpfTable, 0, num * 3 + 2, num * 3 + 4);}
 *          2）水平方向上合并：{@code TableTools.mergeCellsHorizonal(xwpfTable, 2, num * 3 + 2, num * 3 + 4);}
 * </pre>
 * @author Mr.Zhang
 * @since 1.0
 **/
public class RecommendTablePolicy extends DynamicTableRenderPolicy {

    /**
     * 渲染表格数据
     * @param xwpfTable 表格属性
     * @param data      表格数据
     * @throws Exception 异常信息
     */
    @Override
    public void render(XWPFTable xwpfTable, Object data) throws Exception {
        if (null == data) return;
        List<RowRenderData> detailData = (List<RowRenderData>) data;
        xwpfTable.removeRow(2);

        for (int i = detailData.size() - 1; i >= 0; i--) {
            XWPFTableRow newRow = xwpfTable.insertNewTableRow(2);
//            newRow.setHeight(1000);
            for (int j = 0; j < detailData.get(0).getCells().size(); j++) {
                newRow.createCell();// 根据列的数量创建对应单元格
            }
            TableRenderPolicy.Helper.renderRow(newRow, detailData.get(i));
        }

        for (int num = 0; num <= detailData.size() / 3 - 1; num++) {
            TableTools.mergeCellsVertically(xwpfTable, 0, num * 3 + 2, num * 3 + 4);
            TableTools.mergeCellsVertically(xwpfTable, 1, num * 3 + 2, num * 3 + 4);
            TableTools.mergeCellsVertically(xwpfTable, 2, num * 3 + 2, num * 3 + 4);
            TableTools.mergeCellsVertically(xwpfTable, 3, num * 3 + 2, num * 3 + 4);
            TableTools.mergeCellsVertically(xwpfTable, 4, num * 3 + 2, num * 3 + 4);
        }
    }

}
